package com.example.mq.demo;

import com.example.mq.common.Consumer;
import com.example.mq.common.MQException;
import com.example.mq.mqclient.Channel;
import com.example.mq.mqclient.Connection;
import com.example.mq.mqclient.ConnectionFactory;
import com.example.mq.mqserver.core.BasicProperties;
import com.example.mq.mqserver.core.ExchangeType;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class DemoConsumer {
    public static void main(String[] args) throws IOException, MQException, InterruptedException {
        log.info("消费者启动！");
        ConnectionFactory factory = new ConnectionFactory();
//        factory.setHost("43.142.48.195");
        factory.setHost("127.0.0.1");

        factory.setPort(18081);
        Connection connection = factory.newConnection();

        // 创建 Channel
        Channel channel = connection.createChannel();

        // 创建 交换机 和 队列（如果存在，则创建，不存在就直接返回，所以生产者和消费者都去创建一下交换机和队列）
        channel.exchangeDeclare("testExchange", ExchangeType.DIRECT, true, false, null);
        channel.queueDeclare("testQueue", true, false, false, null);

        // 订阅消息
        channel.basicConsume("testQueue", false, new Consumer() {
            @Override
            public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws IOException {
                log.info("【开始消费消息】");
                System.out.println("consumerTag=" + consumerTag);
                System.out.println("basicProperties=" + basicProperties);
                String bodyString = new String(body);
                System.out.println("body=" + bodyString);
                log.info("【结束消费消息】");
                channel.basicAck("testQueue", basicProperties.getMessageId());
            }
        });

        // 消费者等待，生产者生成消息，服务器推送消息
        while (true) {
            Thread.sleep(500);
        }
    }
}
